import json
import time
import requests
import golib_cookie
import re
import keep_session
import websocket
import threading

select_cookie = ''

seat_key = ''
lib_id = ''

select_header = {
    'Host': 'wechat.v2.traceint.com',
    'Connection': 'Upgrade',
    'Pragma': 'no-cache',
    'Cache-Control': 'no-cache',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/98.0.4758.102 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) '
                  'WindowsWechat(0x63090551) XWEB/6945 Flue',
    'Upgrade': 'websocket',
    'Origin': 'https://web.traceint.com',
    'Sec-WebSocket-Version': '13',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh',
    'Sec-WebSocket-Key': 'eTYh3AZI8PuXyuPRr65Zbg==',
    'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
    'Cookie': select_cookie
}

select_data = {"operationName": "reserueSeat",
               "query": "mutation reserueSeat($libId: Int!, $seatKey: String!, $captchaCode: String, $captcha: "
                        "String!) {\n userAuth {\n reserve {\n reserueSeat(\n libId: $libId\n seatKey: $seatKey\n "
                        "captchaCode: $captchaCode\n captcha: $captcha\n )\n }\n }\n}",
               "variables": {"seatKey": seat_key, "libId": lib_id, "captchaCode": "", "captcha": ""}}

select_url = 'https://wechat.v2.traceint.com/index.php/graphql/'


def seat_change():
    global seat_key, lib_id, select_data
    with open('seat_and_lib', 'r') as file:
        lines = [file.readline().strip() for _ in range(2)]

    seat_key_match = re.search(r'"seatKey": "(\d+,\d+)"', lines[0])
    lib_id_match = re.search(r'"libId": (\d+)', lines[1])

    if seat_key_match and lib_id_match:
        seat_key = seat_key_match.group(1)
        lib_id = int(lib_id_match.group(1))

    select_data["variables"]["seatKey"] = seat_key
    select_data["variables"]["libId"] = str(lib_id)
    print(select_data)
    select_seat()


def update_cookie():
    global select_header, select_cookie
    select_header["Cookie"] = select_cookie
    seat_change()


def cookie():
    global select_cookie
    while True:
        choice = input("是否需要重新获取cookie yes/no\n")
        if choice == "yes":
            QRCodeUrl = input("Please enter the URL: ")
            code = golib_cookie.get_code(QRCodeUrl)
            select_cookie = golib_cookie.get_cookie_string(code)
            print("\nCookie string: \n")
            print(select_cookie)
            print("------------------------------")
            break
        elif choice == 'no':
            select_cookie = input("请输入cookie")
            break
        else:
            print("输入不合法\n")
    update_cookie()


def select_seat():
    global select_cookie, select_data, select_header, select_url

    struct_openTime = "2023-12-18 08:00:00"
    openTime = time.strptime(struct_openTime, "%Y-%m-%d %H:%M:%S")
    openTime = time.mktime(openTime)
    request_cnt = 0
    while True:
        timestamp = time.time()

        # 转换成localtime
        time_local = time.localtime(timestamp)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        print(dt, struct_openTime)
        if time.time() >= openTime:
            res = requests.post(url=select_url, headers=select_header, json=select_data).text
            text = json.loads(res).get('data', {}).get('userAuth', {}).get('reserve', {}).get('reserueSeat')
            if text is True:
                print("******************************")
                print("恭喜你！选座成功！程序即将结束......")
                print("******************************\n")
                break
        request_cnt += 1
        if request_cnt >= 10:
            break
    print("程序结束成功！")
    print("请求次数" + str(request_cnt))
    quit()


cookie()
